# view_export_page.py
import tkinter as tk
from tkinter import ttk, messagebox
import datetime
from categories import EXPENSE_CATEGORIES
from .base import UIBase

class ViewExportPage(UIBase):
    def __init__(self, parent, db, analysis=None):
        super().__init__(parent, db, analysis)
        self.parent = parent
        
        # 初始化排序相关属性
        self.sort_column_name = None
        self.sort_reverse = False
        
        # 创建笔记本控件（标签页）
        self.notebook = ttk.Notebook(parent)
        self.notebook.pack(fill=tk.BOTH, expand=True)
        
        # 查看记录页面
        self.view_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.view_frame, text="查看记录")
        
        # 数据导出页面
        self.export_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.export_frame, text="数据导出")
        
        # 初始化各页面
        self.create_view_tab()
        self.create_export_tab()
        
    def create_view_tab(self):
        """创建查看记录标签页 - 优化版本"""
        # 筛选条件
        filter_frame = ttk.LabelFrame(self.view_frame, text="筛选条件", padding=10)
        filter_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 第一行：基本筛选
        basic_filter_frame = ttk.Frame(filter_frame)
        basic_filter_frame.pack(fill=tk.X, pady=5)
        
        # 交易类型筛选
        ttk.Label(basic_filter_frame, text="交易类型:").pack(side=tk.LEFT)
        self.view_type_var = tk.StringVar(value="全部")
        type_combo = ttk.Combobox(basic_filter_frame, textvariable=self.view_type_var, width=8, state="readonly")
        type_combo['values'] = ['全部', '支出', '收入']
        type_combo.pack(side=tk.LEFT, padx=5)
        
        # 分类筛选
        ttk.Label(basic_filter_frame, text="支出分类:").pack(side=tk.LEFT, padx=(20,0))
        self.view_category_var = tk.StringVar(value="全部")
        category_combo = ttk.Combobox(basic_filter_frame, textvariable=self.view_category_var, width=12, state="readonly")
        category_combo['values'] = ['全部'] + list(EXPENSE_CATEGORIES.keys())
        category_combo.pack(side=tk.LEFT, padx=5)
        
        # 排序选项
        ttk.Label(basic_filter_frame, text="排序:").pack(side=tk.LEFT, padx=(20,0))
        self.sort_order_var = tk.StringVar(value="倒序")
        sort_combo = ttk.Combobox(basic_filter_frame, textvariable=self.sort_order_var, width=8, state="readonly")
        sort_combo['values'] = ['正序', '倒序']
        sort_combo.pack(side=tk.LEFT, padx=5)
        
        # 第二行：日期筛选
        date_filter_frame = ttk.Frame(filter_frame)
        date_filter_frame.pack(fill=tk.X, pady=5)
        
        # 使用 tkcalendar 的日期选择器
        try:
            from tkcalendar import DateEntry
            
            ttk.Label(date_filter_frame, text="开始日期:").pack(side=tk.LEFT)
            self.start_date_entry = DateEntry(date_filter_frame, width=12, background='darkblue', 
                                            foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.start_date_entry.pack(side=tk.LEFT, padx=5)
            
            ttk.Label(date_filter_frame, text="结束日期:").pack(side=tk.LEFT, padx=(20,0))
            self.end_date_entry = DateEntry(date_filter_frame, width=12, background='darkblue', 
                                        foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.end_date_entry.pack(side=tk.LEFT, padx=5)
            
            # 设置默认日期（最近30天）
            end_date = datetime.datetime.now()
            start_date = end_date - datetime.timedelta(days=30)
            self.start_date_entry.set_date(start_date)
            self.end_date_entry.set_date(end_date)
            
        except ImportError:
            # 如果 tkcalendar 不可用，回退到普通输入框
            ttk.Label(date_filter_frame, text="开始日期 (YYYY-MM-DD):").pack(side=tk.LEFT)
            self.start_date_var = tk.StringVar()
            ttk.Entry(date_filter_frame, textvariable=self.start_date_var, width=12).pack(side=tk.LEFT, padx=5)
            
            ttk.Label(date_filter_frame, text="结束日期 (YYYY-MM-DD):").pack(side=tk.LEFT, padx=(20,0))
            self.end_date_var = tk.StringVar()
            ttk.Entry(date_filter_frame, textvariable=self.end_date_var, width=12).pack(side=tk.LEFT, padx=5)
        
        # 第三行：按钮和快速筛选
        button_frame = ttk.Frame(filter_frame)
        button_frame.pack(fill=tk.X, pady=5)
        
        ttk.Button(button_frame, text="查询", command=self.refresh_transactions).pack(side=tk.LEFT)
        
        # 快速筛选按钮
        ttk.Button(button_frame, text="今天", command=lambda: self.set_quick_filter('today')).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="本周", command=lambda: self.set_quick_filter('week')).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="本月", command=lambda: self.set_quick_filter('month')).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="今年", command=lambda: self.set_quick_filter('year')).pack(side=tk.LEFT, padx=5)
        
        # 实时汇总信息
        self.summary_frame = ttk.LabelFrame(self.view_frame, text="实时汇总", padding=10)
        self.summary_frame.pack(fill=tk.X, padx=10, pady=5)
        
        summary_content = ttk.Frame(self.summary_frame)
        summary_content.pack(fill=tk.X)
        
        self.summary_income_label = ttk.Label(summary_content, text="总收入: 0.00 元", font=("Arial", 10))
        self.summary_income_label.pack(side=tk.LEFT, padx=20)
        
        self.summary_expense_label = ttk.Label(summary_content, text="总支出: 0.00 元", font=("Arial", 10))
        self.summary_expense_label.pack(side=tk.LEFT, padx=20)
        
        self.summary_balance_label = ttk.Label(summary_content, text="结余: 0.00 元", font=("Arial", 10, "bold"))
        self.summary_balance_label.pack(side=tk.LEFT, padx=20)
        
        self.summary_count_label = ttk.Label(summary_content, text="记录数: 0", font=("Arial", 10))
        self.summary_count_label.pack(side=tk.LEFT, padx=20)
        
        # 交易记录表格
        table_frame = ttk.Frame(self.view_frame)
        table_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 创建树形视图
        columns = ("日期", "时间", "类型", "金额", "大类", "分类", "具体项目", "备注")
        self.transaction_tree = ttk.Treeview(table_frame, columns=columns, show="headings")
        
        # 设置列标题
        column_widths = {
            "日期": 100, "时间": 80, "类型": 60, "金额": 100, 
            "大类": 100, "分类": 120, "具体项目": 150, "备注": 200
        }
        
        for col in columns:
            self.transaction_tree.heading(col, text=col, command=lambda c=col: self.sort_column(c))
            self.transaction_tree.column(col, width=column_widths.get(col, 100))
        
        # 添加滚动条
        v_scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.transaction_tree.yview)
        h_scrollbar = ttk.Scrollbar(table_frame, orient=tk.HORIZONTAL, command=self.transaction_tree.xview)
        self.transaction_tree.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set)
        
        # 布局
        self.transaction_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        v_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 右键菜单
        self.create_context_menu()
        
        # 初始加载数据
        self.refresh_transactions()
        
        # 存储当前排序列和顺序
        self.sort_column_name = None
        self.sort_reverse = False

    def sort_column(self, col):
        """点击列标题时对数据进行排序"""
        # 判断是否点击的是同一列
        if self.sort_column_name == col:
            # 如果是同一列，则切换排序方向
            self.sort_reverse = not self.sort_reverse
        else:
            # 如果是不同列，则重置为降序排序
            self.sort_column_name = col
            self.sort_reverse = True
            
        # 刷新数据显示
        self.refresh_transactions()

    def create_export_tab(self):
        """创建数据导出标签页"""
        # 导出交易记录区域
        export_trans_frame = ttk.LabelFrame(self.export_frame, text="导出交易记录", padding=10)
        export_trans_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 日期筛选
        date_frame = ttk.Frame(export_trans_frame)
        date_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(date_frame, text="日期范围:").pack(side=tk.LEFT)
        
        # 使用 tkcalendar 的日期选择器
        try:
            from tkcalendar import DateEntry
            
            ttk.Label(date_frame, text="从:").pack(side=tk.LEFT, padx=(10,0))
            self.export_start_date_entry = DateEntry(date_frame, width=12, background='darkblue',
                                                foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.export_start_date_entry.pack(side=tk.LEFT, padx=5)
            
            ttk.Label(date_frame, text="到:").pack(side=tk.LEFT, padx=(10,0))
            self.export_end_date_entry = DateEntry(date_frame, width=12, background='darkblue',
                                                foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.export_end_date_entry.pack(side=tk.LEFT, padx=5)
            
            # 设置默认日期（最近30天）
            end_date = datetime.datetime.now()
            start_date = end_date - datetime.timedelta(days=30)
            self.export_start_date_entry.set_date(start_date)
            self.export_end_date_entry.set_date(end_date)
            
        except ImportError:
            # 如果 tkcalendar 不可用，回退到普通输入框
            ttk.Label(date_frame, text="开始日期 (YYYY-MM-DD):").pack(side=tk.LEFT, padx=(10,0))
            self.export_start_date = tk.StringVar()
            ttk.Entry(date_frame, textvariable=self.export_start_date, width=12).pack(side=tk.LEFT, padx=5)
            
            ttk.Label(date_frame, text="结束日期 (YYYY-MM-DD):").pack(side=tk.LEFT, padx=(10,0))
            self.export_end_date = tk.StringVar()
            ttk.Entry(date_frame, textvariable=self.export_end_date, width=12).pack(side=tk.LEFT, padx=5)
        
        # 导出按钮
        ttk.Button(export_trans_frame, text="导出交易记录", 
                command=self.export_transactions).pack(side=tk.LEFT, pady=10)
        
        # 导出汇总数据区域
        export_summary_frame = ttk.LabelFrame(self.export_frame, text="导出汇总数据", padding=10)
        export_summary_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 汇总数据日期范围筛选
        summary_date_frame = ttk.Frame(export_summary_frame)
        summary_date_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(summary_date_frame, text="日期范围:").pack(side=tk.LEFT)
        
        try:
            from tkcalendar import DateEntry
            
            ttk.Label(summary_date_frame, text="从:").pack(side=tk.LEFT, padx=(10,0))
            self.summary_export_start_date_entry = DateEntry(summary_date_frame, width=12, background='darkblue',
                                                foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.summary_export_start_date_entry.pack(side=tk.LEFT, padx=5)
            
            ttk.Label(summary_date_frame, text="到:").pack(side=tk.LEFT, padx=(10,0))
            self.summary_export_end_date_entry = DateEntry(summary_date_frame, width=12, background='darkblue',
                                                foreground='white', borderwidth=2, date_pattern='y-mm-dd')
            self.summary_export_end_date_entry.pack(side=tk.LEFT, padx=5)
            
            # 设置默认日期（最近12个月）
            end_date = datetime.datetime.now()
            start_date = end_date - datetime.timedelta(days=365)
            self.summary_export_start_date_entry.set_date(start_date)
            self.summary_export_end_date_entry.set_date(end_date)
            
        except ImportError:
            ttk.Label(summary_date_frame, text="开始日期 (YYYY-MM-DD):").pack(side=tk.LEFT, padx=(10,0))
            self.summary_export_start_date = tk.StringVar()
            ttk.Entry(summary_date_frame, textvariable=self.summary_export_start_date, width=12).pack(side=tk.LEFT, padx=5)
            
            ttk.Label(summary_date_frame, text="结束日期 (YYYY-MM-DD):").pack(side=tk.LEFT, padx=(10,0))
            self.summary_export_end_date = tk.StringVar()
            ttk.Entry(summary_date_frame, textvariable=self.summary_export_end_date, width=12).pack(side=tk.LEFT, padx=5)
        
        summary_frame = ttk.Frame(export_summary_frame)
        summary_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(summary_frame, text="汇总周期:").pack(side=tk.LEFT)
        
        self.export_period = tk.StringVar(value="月")
        period_combo = ttk.Combobox(summary_frame, textvariable=self.export_period, 
                                width=8, state="readonly")
        period_combo['values'] = ['日', '周', '月', '季', '年']
        period_combo.pack(side=tk.LEFT, padx=5)
        
        ttk.Button(summary_frame, text="导出汇总数据", 
                command=self.export_summary).pack(side=tk.LEFT, padx=10, pady=10)
        
        # 导出状态显示
        self.export_status = tk.StringVar(value="就绪")
        self.export_status_label = ttk.Label(self.export_frame, textvariable=self.export_status)
        self.export_status_label.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=5)
        
        # 导出历史记录区域
        history_frame = ttk.LabelFrame(self.export_frame, text="导出历史", padding=10)
        history_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 创建导出历史表格
        columns = ("时间", "类型", "日期范围", "文件路径")
        self.export_history_tree = ttk.Treeview(history_frame, columns=columns, show="headings")
        
        for col in columns:
            self.export_history_tree.heading(col, text=col)
            self.export_history_tree.column(col, width=150)
        
        history_scrollbar = ttk.Scrollbar(history_frame, orient=tk.VERTICAL, 
                                        command=self.export_history_tree.yview)
        self.export_history_tree.configure(yscrollcommand=history_scrollbar.set)
        
        self.export_history_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        history_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 加载导出历史
        self.load_export_history() 

    def load_export_history(self):
        """加载导出历史记录"""
        # 这里可以实现从文件或数据库加载导导出历史记录
        # 暂时留空，可以根据需要实现
        pass

    def add_export_history(self, export_type, start_date, end_date, file_path):
        """添加导出历史记录"""
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        date_range = f"{start_date or '全部'}至{end_date or '全部'}" if start_date or end_date else "全部数据"
        
        self.export_history_tree.insert("", "end", values=(
            now,
            export_type,
            date_range,
            file_path
        ))

    def create_context_menu(self):
        """创建右键菜单"""
        self.context_menu = tk.Menu(self.parent, tearoff=0)
        self.context_menu.add_command(label="删除记录", command=self.delete_selected_record)
        self.context_menu.add_command(label="查看详情", command=self.view_record_detail)
        
        # 绑定右键事件
        self.transaction_tree.bind("<Button-3>", self.show_context_menu)

    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.transaction_tree.identify_row(event.y)
        if item:
            self.transaction_tree.selection_set(item)
            self.context_menu.post(event.x_root, event.y_root)

    def delete_selected_record(self):
        """删除选中的记录"""
        selected_item = self.transaction_tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请先选择要删除的记录")
            return
        
        if messagebox.askyesno("确认删除", "确定要删除选中的记录吗？此操作不可撤销。"):
            # 获取选中记录的信息
            item_values = self.transaction_tree.item(selected_item[0], 'values')
            date = item_values[0]
            time = item_values[1]
            amount = float(item_values[3])
            
            # 查找记录ID
            transaction = self.db.get_transaction_by_details(date, time, amount)
            
            if transaction:
                success = self.db.delete_transaction(transaction['id'])
                if success:
                    messagebox.showinfo("成功", f"已删除 {date} {time} 的记录")
                    self.refresh_transactions()
                else:
                    messagebox.showerror("错误", "删除记录失败")
            else:
                messagebox.showerror("错误", "未找到对应的记录")

    def view_record_detail(self):
        """查看记录详情"""
        selected_item = self.transaction_tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请先选择要查看的记录")
            return
        
        item_values = self.transaction_tree.item(selected_item[0], 'values')
        
        detail_window = tk.Toplevel(self.parent)
        detail_window.title("记录详情")
        detail_window.geometry("400x300")
        
        # 显示详细信息
        details = [
            f"日期: {item_values[0]}",
            f"时间: {item_values[1]}",
            f"类型: {item_values[2]}",
            f"金额: {item_values[3]} 元",
            f"大类: {item_values[4]}",
            f"分类: {item_values[5]}",
            f"具体项目: {item_values[6]}",
            f"备注: {item_values[7]}"
        ]
        
        for i, detail in enumerate(details):
            ttk.Label(detail_window, text=detail, font=("Arial", 11)).pack(anchor=tk.W, padx=20, pady=5)

    def set_quick_filter(self, period: str):
        """设置快速筛选"""
        today = datetime.datetime.now()
        
        if period == 'today':
            start_date = today
            end_date = today
        elif period == 'week':
            start_date = today - datetime.timedelta(days=today.weekday())
            end_date = start_date + datetime.timedelta(days=6)
        elif period == 'month':
            start_date = today.replace(day=1)
            if today.month == 12:
                end_date = today.replace(year=today.year+1, month=1, day=1) - datetime.timedelta(days=1)
            else:
                end_date = today.replace(month=today.month+1, day=1) - datetime.timedelta(days=1)
        elif period == 'year':
            start_date = today.replace(month=1, day=1)
            end_date = today.replace(month=12, day=31)
        
        # 设置日期选择器
        try:
            self.start_date_entry.set_date(start_date)
            self.end_date_entry.set_date(end_date)
        except:
            # 如果使用普通输入框
            self.start_date_var.set(start_date.strftime("%Y-%m-%d"))
            self.end_date_var.set(end_date.strftime("%Y-%m-%d"))
        
        # 自动刷新
        self.refresh_transactions()

    def refresh_transactions(self):
        """刷新交易记录显示和汇总"""
        # 清空现有数据
        for item in self.transaction_tree.get_children():
            self.transaction_tree.delete(item)
        
        # 获取筛选条件
        try:
            start_date = self.start_date_entry.get_date().strftime("%Y-%m-%d")
            end_date = self.end_date_entry.get_date().strftime("%Y-%m-%d")
        except:
            start_date = self.start_date_var.get() or None
            end_date = self.end_date_var.get() or None
        
        view_type = self.view_type_var.get()
        category = self.view_category_var.get()
        sort_order = self.sort_order_var.get()
        
        # 获取交易记录
        transactions = self.db.get_transactions(start_date, end_date)
        
        # 筛选数据
        filtered_transactions = []
        total_income = 0
        total_expense = 0
        
        for transaction in transactions:
            # 类型筛选
            if view_type == '支出' and transaction['type'] != 'expense':
                continue
            if view_type == '收入' and transaction['type'] != 'income':
                continue
            
            # 分类筛选
            if category != '全部' and transaction['main_category'] != category:
                continue
            
            filtered_transactions.append(transaction)
            
            # 计算汇总
            if transaction['type'] == 'income':
                total_income += transaction['amount']
            else:
                total_expense += transaction['amount']
                
        # 根据排序选项排序
        if self.sort_column_name:
            # 确定用于排序的列索引
            column_mapping = {
                "日期": "date",
                "时间": "time", 
                "类型": "type",
                "金额": "amount",
                "大类": "main_category",
                "分类": "sub_category",
                "具体项目": "item_detail",
                "备注": "note"
            }
            
            key = column_mapping.get(self.sort_column_name)
            if key:
                # 对于不同类型字段采用不同的排序方式
                if key == "amount":
                    # 数值类型排序
                    filtered_transactions.sort(key=lambda x: x[key], reverse=self.sort_reverse)
                elif key in ["date", "time"]:
                    # 时间类型排序
                    filtered_transactions.sort(key=lambda x: x[key], reverse=self.sort_reverse)
                else:
                    # 字符串类型排序
                    filtered_transactions.sort(key=lambda x: str(x[key]).lower(), reverse=self.sort_reverse)
        else:
            # 默认按日期倒序排列
            if sort_order == "倒序":
                filtered_transactions.sort(key=lambda x: (x['date'], x['time']), reverse=True)
            else:
                filtered_transactions.sort(key=lambda x: (x['date'], x['time']), reverse=False)
        
        # 添加数据到表格
        for transaction in filtered_transactions:
            type_text = "收入" if transaction['type'] == 'income' else "支出"
            # 金额保留两位小数显示
            amount_text = f"{transaction['amount']:.2f}"
            
            # 设置行颜色
            tags = ('income',) if transaction['type'] == 'income' else ('expense',)
            
            self.transaction_tree.insert("", "end", values=(
                transaction['date'],
                transaction['time'],
                type_text,
                amount_text,
                transaction['main_category'],
                transaction['sub_category'],
                transaction['item_detail'] or "",
                transaction['note'] or ""
            ), tags=tags)
        
        # 设置行颜色
        self.transaction_tree.tag_configure('income', foreground='green')
        self.transaction_tree.tag_configure('expense', foreground='red')
        
        # 更新汇总信息，保留两位小数
        balance = total_income - total_expense
        self.summary_income_label.config(text=f"总收入: {total_income:.2f} 元")
        self.summary_expense_label.config(text=f"总支出: {total_expense:.2f} 元")
        self.summary_balance_label.config(text=f"结余: {balance:.2f} 元")
        self.summary_count_label.config(text=f"记录数: {len(filtered_transactions)}")
        
        # 根据余额设置颜色
        if balance >= 0:
            self.summary_balance_label.config(foreground='green')
        else:
            self.summary_balance_label.config(foreground='red')
    

    def export_transactions(self):
        """导出交易记录"""
        try:
            # 选择保存路径
            file_path = self._open_save_dialog(
                "保存交易记录",
                f"记账数据_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
            )
            
            if not file_path:
                return
            
            # 获取日期范围
            try:
                start_date = self.export_start_date_entry.get_date().strftime("%Y-%m-%d")
                end_date = self.export_end_date_entry.get_date().strftime("%Y-%m-%d")
            except:
                start_date = self.export_start_date.get() or None
                end_date = self.export_end_date.get() or None
            
            # 更新状态
            if start_date and end_date:
                self.export_status.set(f"正在导出 {start_date} 至 {end_date} 的交易记录...")
            else:
                self.export_status.set("正在导出全部交易记录...")
            
            self.parent.update()  # 更新界面显示状态
            
            success = self.db.export_to_csv(file_path, start_date, end_date)
            
            if success:
                self.export_status.set(f"导出成功！文件已保存到: {file_path}")
                self.add_export_history("交易记录", start_date, end_date, file_path)
            else:
                self.export_status.set("导出失败，没有数据可导出")
                
        except Exception as e:
            messagebox.showerror("导出错误", f"导出失败: {str(e)}")
            self.export_status.set("导出失败")

    def export_summary(self):
        """导出汇总数据"""
        try:
            # 选择保存路径
            period_display = self.export_period.get()
            file_path = self._open_save_dialog(
                "保存汇总数据",
                f"记账汇总_{period_display}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
            )
            
            if not file_path:
                return
            
            # 获取日期范围
            try:
                start_date = self.summary_export_start_date_entry.get_date().strftime("%Y-%m-%d")
                end_date = self.summary_export_end_date_entry.get_date().strftime("%Y-%m-%d")
            except:
                start_date = self.summary_export_start_date.get() or None
                end_date = self.summary_export_end_date.get() or None
            
            # 映射周期参数
            period_map = {'日': 'day', '周': 'week', '月': 'month', '季': 'quarter', '年': 'year'}
            period = period_map.get(self.export_period.get(), 'month')
            
            # 更新状态
            if start_date and end_date:
                self.export_status.set(f"正在导出 {start_date} 至 {end_date} 的{self.export_period.get()}度汇总数据...")
            else:
                self.export_status.set(f"正在导出全部{self.export_period.get()}度汇总数据...")
            
            self.parent.update()  # 更新界面显示状态
            
            success = self.db.export_summary_to_csv(file_path, period, start_date, end_date)
            
            if success:
                date_range = f"{start_date}至{end_date}" if start_date and end_date else "全部数据"
                self.export_status.set(f"导出成功！文件已保存到: {file_path}")
                self.add_export_history(f"{self.export_period.get()}度汇总", start_date, end_date, file_path)
            else:
                self.export_status.set("导出失败，没有数据可导出")
                
        except Exception as e:
            messagebox.showerror("导出错误", f"导出失败: {str(e)}")
            self.export_status.set("导出失败")